/**
 * 后台管理界面JavaScript功能
 * 包含登录页面和后台管理的交互功能
 */
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initCommonFeatures();
    
    // 根据页面类型初始化特定功能
    if (document.body.classList.contains('login-page')) {
        initLoginPage();
    } else if (document.body.classList.contains('admin-page')) {
        initAdminPage();
    }
});

/**
 * 初始化通用功能
 */
function initCommonFeatures() {
    // 添加加载动画
    addLoadingAnimation();
    
    // 初始化表单验证
    initFormValidation();
    
    // 初始化提示消息自动消失
    initAlertAutoHide();
}

/**
 * 初始化登录页面功能
 */
function initLoginPage() {
    const loginForm = document.querySelector('.login-form');
    const usernameInput = document.querySelector('#username');
    const passwordInput = document.querySelector('#password');
    const submitBtn = loginForm?.querySelector('button[type="submit"]');
    
    if (!loginForm) return;
    
    // 添加输入框动画效果
    [usernameInput, passwordInput].forEach(input => {
        if (input) {
            input.addEventListener('focus', function() {
                this.parentElement.classList.add('focused');
            });
            
            input.addEventListener('blur', function() {
                if (!this.value) {
                    this.parentElement.classList.remove('focused');
                }
            });
            
            // 检查是否有初始值
            if (input.value) {
                input.parentElement.classList.add('focused');
            }
        }
    });
    
    // 登录表单提交处理
    loginForm.addEventListener('submit', function(e) {
        const username = usernameInput?.value.trim();
        const password = passwordInput?.value.trim();
        
        if (!username || !password) {
            e.preventDefault();
            showAlert('请填写用户名和密码', 'error');
            return;
        }
        
        // 添加加载状态
        if (submitBtn) {
            submitBtn.classList.add('loading');
            submitBtn.disabled = true;
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
            
            // 如果3秒后还没有响应，恢复按钮状态
            setTimeout(() => {
                if (submitBtn.disabled) {
                    submitBtn.classList.remove('loading');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            }, 3000);
        }
    });
    
    // 键盘快捷键支持 - 修复回车键逻辑
    if (usernameInput) {
        usernameInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault(); // 阻止默认的表单提交
                // 将焦点移动到密码输入框
                if (passwordInput) {
                    passwordInput.focus();
                }
            }
        });
    }
    
    if (passwordInput) {
        passwordInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                // 在密码框按回车才提交表单
                const username = usernameInput?.value.trim();
                const password = passwordInput?.value.trim();
                
                if (!username || !password) {
                    e.preventDefault();
                    showAlert('请填写用户名和密码', 'error');
                    return;
                }
                
                // 允许正常提交表单
                loginForm.submit();
            }
        });
    }
}

/**
 * 初始化后台管理页面功能
 */
function initAdminPage() {
    // 初始化侧边栏
    initSidebar();
    
    // 初始化模态框
    initModals();
    
    // 初始化表格功能
    initTables();
    
    // 初始化时间显示
    updateDateTime();
    setInterval(updateDateTime, 1000);
    
    // 初始化仪表盘功能
    initDashboard();
}

/**
 * 初始化侧边栏功能
 */
function initSidebar() {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('open');
        });
    }
    
    // 移动端点击外部关闭侧边栏
    document.addEventListener('click', function(e) {
        if (window.innerWidth <= 768) {
            if (!sidebar?.contains(e.target) && !sidebarToggle?.contains(e.target)) {
                sidebar?.classList.remove('open');
            }
        }
    });
}

/**
 * 初始化模态框功能
 */
function initModals() {
    // 打开模态框
    document.addEventListener('click', function(e) {
        const trigger = e.target.closest('[data-modal]');
        if (trigger) {
            const modalId = trigger.getAttribute('data-modal');
            const modal = document.getElementById(modalId);
            if (modal) {
                openModal(modal);
            }
        }
    });
    
    // 关闭模态框
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal') || e.target.classList.contains('close-btn')) {
            const modal = e.target.closest('.modal');
            if (modal) {
                closeModal(modal);
            }
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal.show');
            if (openModal) {
                closeModal(openModal);
            }
        }
    });
}

/**
 * 打开模态框
 */
function openModal(modal) {
    modal.classList.add('show');
    document.body.style.overflow = 'hidden';
    
    // 聚焦到第一个输入框
    const firstInput = modal.querySelector('input, textarea, select');
    if (firstInput) {
        setTimeout(() => firstInput.focus(), 100);
    }
}

/**
 * 关闭模态框
 */
function closeModal(modal) {
    modal.classList.remove('show');
    document.body.style.overflow = '';
    
    // 重置表单
    const form = modal.querySelector('form');
    if (form) {
        form.reset();
    }
}

/**
 * 初始化表格功能
 */
function initTables() {
    // 表格排序
    document.querySelectorAll('.table th[data-sort]').forEach(th => {
        th.addEventListener('click', function() {
            const table = this.closest('table');
            const column = this.getAttribute('data-sort');
            sortTable(table, column, this);
        });
    });
    
    // 批量操作
    initBatchOperations();
}

/**
 * 表格排序功能
 */
function sortTable(table, column, th) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const isAsc = th.classList.contains('sort-asc');
    
    // 重置所有排序标记
    table.querySelectorAll('th').forEach(header => {
        header.classList.remove('sort-asc', 'sort-desc');
    });
    
    // 设置当前排序标记
    th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
    
    const columnIndex = Array.from(th.parentElement.children).indexOf(th);
    
    rows.sort((a, b) => {
        const aVal = a.children[columnIndex]?.textContent.trim() || '';
        const bVal = b.children[columnIndex]?.textContent.trim() || '';
        
        const result = aVal.localeCompare(bVal, undefined, { numeric: true });
        return isAsc ? -result : result;
    });
    
    // 重新插入排序后的行
    rows.forEach(row => tbody.appendChild(row));
}

/**
 * 初始化批量操作
 */
function initBatchOperations() {
    const selectAll = document.querySelector('.select-all');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    const batchActions = document.querySelector('.batch-actions');
    
    if (selectAll) {
        selectAll.addEventListener('change', function() {
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            toggleBatchActions();
        });
    }
    
    rowCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', toggleBatchActions);
    });
    
    function toggleBatchActions() {
        const checkedCount = document.querySelectorAll('.row-checkbox:checked').length;
        if (batchActions) {
            batchActions.style.display = checkedCount > 0 ? 'block' : 'none';
        }
        
        if (selectAll) {
            selectAll.indeterminate = checkedCount > 0 && checkedCount < rowCheckboxes.length;
            selectAll.checked = checkedCount === rowCheckboxes.length;
        }
    }
}

/**
 * 初始化仪表盘功能
 */
function initDashboard() {
    // 初始化图表
    initCharts();
    
    // 初始化数字显示
    initCounterDisplay();
    
    // 初始化实时数据刷新
    initRealTimeUpdates();
}

/**
 * 初始化图表
 */
function initCharts() {
    const chartCanvas = document.getElementById('visitsChart');
    if (!chartCanvas || !window.Chart) return;
    
    // 获取最近30天的数据
    const dailyVisits = window.STATS_DATA?.dailyVisits || {};
    const last30Days = getLast30Days();
    const chartData = last30Days.map(date => dailyVisits[date] || 0);
    const chartLabels = last30Days.map(date => {
        const d = new Date(date);
        return `${d.getMonth() + 1}/${d.getDate()}`;
    });
    
    const ctx = chartCanvas.getContext('2d');
    
    // 创建渐变
    const gradient = ctx.createLinearGradient(0, 0, 0, 300);
    gradient.addColorStop(0, 'rgba(0, 122, 255, 0.3)');
    gradient.addColorStop(1, 'rgba(0, 122, 255, 0.05)');
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartLabels,
            datasets: [{
                label: '访问量',
                data: chartData,
                borderColor: '#007AFF',
                backgroundColor: gradient,
                borderWidth: 3,
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#007AFF',
                pointBorderColor: '#FFFFFF',
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#FFFFFF',
                    bodyColor: '#FFFFFF',
                    borderColor: '#007AFF',
                    borderWidth: 1,
                    cornerRadius: 8,
                    displayColors: false
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: '#86868B'
                    }
                },
                y: {
                    grid: {
                        color: '#E5E5EA'
                    },
                    ticks: {
                        color: '#86868B',
                        beginAtZero: true
                    }
                }
            },
            elements: {
                point: {
                    hoverBackgroundColor: '#007AFF'
                }
            }
        }
    });
}

/**
 * 获取最近30天的日期数组
 */
function getLast30Days() {
    const dates = [];
    const today = new Date();
    
    for (let i = 29; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(date.getDate() - i);
        dates.push(date.toISOString().split('T')[0]);
    }
    
    return dates;
}

/**
 * 初始化数字显示
 */
function initCounterDisplay() {
    const counters = document.querySelectorAll('.stats-cards .card-content h3');
    
    counters.forEach(counter => {
        const target = parseInt(counter.textContent.replace(/,/g, ''));
        if (isNaN(target)) return;
        
        // 直接显示最终数字，不使用动画效果
        counter.textContent = target.toLocaleString();
    });
}

/**
 * 初始化实时数据刷新
 */
function initRealTimeUpdates() {
    // 每5分钟刷新一次统计数据
    setInterval(refreshDashboardData, 5 * 60 * 1000);
}

/**
 * 刷新仪表盘数据
 */
function refreshDashboardData() {
    fetch(window.CONFIG?.apiUrl + 'stats')
        .then(response => response.json())
        .then(data => {
            updateStatsCards(data);
        })
        .catch(error => {
            console.error('刷新数据失败:', error);
        });
}

/**
 * 更新统计卡片
 */
function updateStatsCards(data) {
    const cards = document.querySelectorAll('.stats-cards .card-content h3');
    
    if (cards[0] && data.total_visits) {
        cards[0].textContent = Number(data.total_visits).toLocaleString();
    }
    if (cards[1] && data.today_visits) {
        cards[1].textContent = Number(data.today_visits).toLocaleString();
    }
    if (cards[2] && data.search_count) {
        cards[2].textContent = Number(data.search_count).toLocaleString();
    }
}

/**
 * 更新时间显示
 */
function updateDateTime() {
    const timeElement = document.querySelector('.datetime .time');
    const dateElement = document.querySelector('.datetime .date');
    
    if (timeElement || dateElement) {
        const now = new Date();
        
        if (timeElement) {
            timeElement.textContent = now.toLocaleTimeString('zh-CN', {
                hour12: false,
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }
        
        if (dateElement) {
            dateElement.textContent = now.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            });
        }
    }
    
    // 更新页面中的其他时间元素
    updateCurrentTime();
    updateCurrentDate();
}

/**
 * 更新当前时间显示
 */
function updateCurrentTime() {
    const timeElement = document.getElementById('currentTime');
    if (timeElement) {
        const now = new Date();
        timeElement.textContent = now.toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }
}

/**
 * 更新当前日期显示
 */
function updateCurrentDate() {
    const dateElement = document.getElementById('currentDate');
    if (dateElement) {
        const now = new Date();
        dateElement.textContent = now.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long'
        });
    }
}

/**
 * 初始化表单验证
 */
function initFormValidation() {
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
            }
        });
    });
}

/**
 * 表单验证
 */
function validateForm(form) {
    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            showFieldError(field, '此字段为必填项');
            isValid = false;
        } else {
            clearFieldError(field);
        }
    });
    
    return isValid;
}

/**
 * 显示字段错误
 */
function showFieldError(field, message) {
    clearFieldError(field);
    
    const errorElement = document.createElement('div');
    errorElement.className = 'field-error';
    errorElement.textContent = message;
    
    field.parentElement.appendChild(errorElement);
    field.classList.add('error');
}

/**
 * 清除字段错误
 */
function clearFieldError(field) {
    const errorElement = field.parentElement.querySelector('.field-error');
    if (errorElement) {
        errorElement.remove();
    }
    field.classList.remove('error');
}

/**
 * 显示提示消息
 */
function showAlert(message, type = 'info') {
    const alertContainer = document.querySelector('.alert-container') || createAlertContainer();
    
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.innerHTML = `
        <i class="fas fa-${getAlertIcon(type)}"></i>
        ${message}
    `;
    
    alertContainer.appendChild(alert);
    
    // 动画显示
    setTimeout(() => alert.classList.add('show'), 10);
    
    // 自动消失
    setTimeout(() => {
        alert.classList.remove('show');
        setTimeout(() => alert.remove(), 300);
    }, 3000);
}

/**
 * 创建提示消息容器
 */
function createAlertContainer() {
    const container = document.createElement('div');
    container.className = 'alert-container';
    container.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        pointer-events: none;
    `;
    document.body.appendChild(container);
    return container;
}

/**
 * 获取提示图标
 */
function getAlertIcon(type) {
    const icons = {
        success: 'check-circle',
        error: 'exclamation-triangle',
        warning: 'exclamation-circle',
        info: 'info-circle'
    };
    return icons[type] || icons.info;
}

/**
 * 初始化提示消息自动消失
 */
function initAlertAutoHide() {
    document.querySelectorAll('.alert').forEach(alert => {
        setTimeout(() => {
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 300);
        }, 3000);
    });
}

/**
 * 添加加载动画
 */
function addLoadingAnimation() {
    // 页面加载动画
    window.addEventListener('beforeunload', function() {
        document.body.classList.add('loading');
    });
    
    // 表单提交动画
    document.addEventListener('submit', function(e) {
        const form = e.target;
        const submitBtn = form.querySelector('button[type="submit"]');
        
        if (submitBtn && !submitBtn.disabled) {
            submitBtn.classList.add('loading');
            submitBtn.disabled = true;
        }
    });
}

/**
 * 确认对话框
 */
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

/**
 * 复制到剪贴板
 */
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showAlert('已复制到剪贴板', 'success');
    }).catch(() => {
        showAlert('复制失败', 'error');
    });
}

// 导出功能供全局使用
window.AdminJS = {
    showAlert,
    openModal,
    closeModal,
    confirmAction,
    copyToClipboard,
    validateForm
};